package com.iflytek.cosmo.ocr.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.iflytek.cosmo.ocr.common.PageResult;
import com.iflytek.cosmo.ocr.common.config.RestServiceConfig;
import com.iflytek.cosmo.ocr.common.constant.CommonConstant;
import com.iflytek.cosmo.ocr.common.enums.ResultCodeEnum;
import com.iflytek.cosmo.ocr.model.domain.MessageOutput;
import com.iflytek.cosmo.ocr.model.domain.State;
import com.iflytek.cosmo.ocr.model.entity.FeedbackEntity;
import com.iflytek.cosmo.ocr.service.FeedbackService;
import com.iflytek.cosmo.ocr.web.vo.FeedbackVO;
import com.iflytek.cosmo.ocr.web.vo.ReplyVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @className: FeedbackController
 * @Description: 信息反馈接口
 */
@Api(value = "信息反馈API",tags="信息反馈")
@RestController
@RequestMapping("/feedback")
public class FeedbackController {
    private static final Logger logger = LoggerFactory.getLogger(FeedbackController.class);

    /**
     * feedbackService
     */
    @Autowired
    private FeedbackService feedbackService;

    @Autowired
    private RestServiceConfig restServiceConfig;


    @ApiOperation(value = "获取客服信息",notes = "获取客服信息" ,httpMethod = "GET")
    @RequestMapping(value = "/customerServiceInfo",method = RequestMethod.GET)
    public MessageOutput<String> customerServiceInfo()
    {
        try {
            MessageOutput<String> result = MessageOutput.failed(String.class);
            List<Map<String, Object>> customer = restServiceConfig.getCustomer();
            /*List<Map<String, Object>> customerList = FileUtil.deepCopy(customer);
            if(CollectionUtils.isNotEmpty(customerList)){
                customerList.forEach(v->{
                    byte[] name = v.get("name").toString().getBytes(StandardCharsets.ISO_8859_1);
                    v.put("name", new String(name, StandardCharsets.UTF_8));
                });
            }*/
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("serviceInfo",customer);
                String text =  jsonObject.toString();
                result.setBody(text);
                result.setState(new State(ResultCodeEnum.SUCCESS.getCode()));

            }catch (Exception ex){
                result.setState(new State(ResultCodeEnum.FAILED.getCode(), "找客服信息出错"));
                logger.error(ex.toString());
            }finally {
                return  result;
            }
        }catch (Exception ex){
            return null;
        }
    }

    @ApiOperation(value = "提交用户反馈意见",notes = "提交用户反馈意见" ,httpMethod = "POST")
    @RequestMapping(value = "/submitFeedback",method = RequestMethod.POST)
    public MessageOutput<Object> submitFeedback(@RequestBody FeedbackVO feedbackVO){
        if(StringUtils.isAnyEmpty(feedbackVO.getUserId(),feedbackVO.getDescribe(),feedbackVO.getTitle()))
        {
            return new MessageOutput<>(new State(ResultCodeEnum.FAILED.getCode(),"UserId,Describe，Title不能为空"));
        }
        if(feedbackService.submitFeedback(voConvert(feedbackVO)))
            return new MessageOutput<>(new State(ResultCodeEnum.SUCCESS.getCode(), "提交成功"));
        else
            return new MessageOutput<>(new State(ResultCodeEnum.FAILED.getCode(),"提交失败"));
    }

    @ApiOperation(value = "提交回复信息",notes = "提交回复信息" ,httpMethod = "POST")
    @RequestMapping(value = "/submitReply",method = RequestMethod.POST)
    public MessageOutput<Object> submitReply(@RequestBody FeedbackVO feedbackVO){
        try{

            if(null == feedbackVO.getOriginId()|| 0 == feedbackVO.getOriginId())
            {
                return new MessageOutput<>(new State(ResultCodeEnum.FAILED.getCode(),"OriginId不能为空"));
            }
            if(feedbackService.submitReply(voConvert(feedbackVO))){
                return new MessageOutput<>(new State(ResultCodeEnum.SUCCESS.getCode(), "提交成功"));
            }
            else
                return new MessageOutput<>(new State(ResultCodeEnum.FAILED.getCode(),"提交失败"));
        }catch (Exception ex)
        {
            logger.error("插入回复数据出错" +  ex.getMessage());
            return  new MessageOutput<>(new State(ResultCodeEnum.FAILED.getCode(),"提交回复数据出错已经回滚"));
        }

    }

    @ApiOperation(value = "获取反馈列表",notes = "获取反馈列表",httpMethod = "GET")
    @RequestMapping(value = "/feedbacksInfo",method = RequestMethod.GET)
    public MessageOutput<Object> feedbacksInfo( @RequestParam(name = "userId", required = true) String userId)
    {
        if(StringUtils.isEmpty(userId))
            return new MessageOutput<>(new State(ResultCodeEnum.MISSING_REQUIRED_PARAMS.getCode(),ResultCodeEnum.MISSING_REQUIRED_PARAMS.getDesc()));
        List<FeedbackEntity> feedbackEntityList = feedbackService.getComments(userId); //查询出用户评论
        if(CollectionUtils.isEmpty(feedbackEntityList))
            return new MessageOutput<>(new State(ResultCodeEnum.FAILED.getCode(),"没有评论"));
        List<ReplyVO> replyList = new ArrayList<>();
        feedbackEntityList.forEach(feedbackEntity -> {
            ReplyVO reply = new ReplyVO();
            reply.setId(feedbackEntity.getId());
            reply.setTitle(feedbackEntity.getTitle());
            reply.setQuestion(feedbackEntity.getContent());
            reply.setCreateTime(feedbackEntity.getCreateTime());
            List<FeedbackEntity> replysList = feedbackService.getReply(feedbackEntity.getId()).stream().sorted(Comparator.comparing(FeedbackEntity::getCreateTime)).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(replysList)){
                replysList.forEach(v->{
                    reply.getReplyList().add(v.getContent());
                });
            }
            replyList.add(reply);
        });
        replyList.sort((r1,r2)->r2.getCreateTime().compareTo(r1.getCreateTime()));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("replyInfo",replyList);
        String text =  JSONObject.toJSONString(jsonObject);
        MessageOutput<Object> result = new MessageOutput<>(new State(ResultCodeEnum.SUCCESS.getCode()),text);
        return result;
    }

    @ApiOperation(value = "获取用户的所有反馈",notes = "获取用户的所有反馈 0已提交 1已回复 2未回复 1已删除 2未删除" ,httpMethod = "GET")
    @RequestMapping(value = "/feedbackList",method = RequestMethod.GET)
    public MessageOutput<PageResult<FeedbackVO>> getFeedbackList(@RequestParam(required = false) String userId,
                                                                 @RequestParam(required = false) String name,
                                                                 @RequestParam(required = false) String companyName,
                                                                 @RequestParam(required = false, defaultValue = "0") Integer replyStatus,
                                                                 @RequestParam(required = false, defaultValue = "0") Integer deleteStatus,
                                                                 @RequestParam(required = false, defaultValue = "1") Integer page,
                                                                 @RequestParam(required = false, defaultValue = "10") Integer size,
                                                                 HttpServletRequest request){
        PageResult<FeedbackVO> pageResult = new PageResult<>(page, size);

        //分页获取回复列表
        PageResult<FeedbackEntity> feedbcakResult = feedbackService.getFeedbcakList(userId,companyName,name,replyStatus,deleteStatus,page,size);
        /*String feedbacksId = feedbcakList.stream().map(FeedbackEntity::getId).collect(Collectors.toList()).stream().map(x -> x + "").collect(Collectors.toList())
                .stream().collect(Collectors.joining(","));*/
        if (CollectionUtils.isEmpty(feedbcakResult.getData())) {
            return  new MessageOutput<>(new State(ResultCodeEnum.SUCCESS.getCode()));
        }
        pageResult.setTotal(feedbcakResult.getTotal());

        //获取回复列表
        List<Integer> feedbacksIdList = feedbcakResult.getData().stream().map(FeedbackEntity::getId).collect(Collectors.toList());
        List<FeedbackEntity> replyList = feedbackService.getReplyList(feedbacksIdList).stream().sorted(Comparator.comparing(FeedbackEntity::getCreateTime)).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(replyList)) {
            Map<Integer, List<FeedbackEntity>> replyMap = replyList.stream().collect(Collectors.groupingBy(FeedbackEntity::getOriginId));
            pageResult.setData(feedbcakResult.getData().stream().map(f -> convert(f, replyMap.get(f.getId()))).sorted((r1,r2)->r2.getCreateTime().compareTo(r1.getCreateTime())).collect(Collectors.toList()));
        } else {
            pageResult.setData(feedbcakResult.getData().stream().map(f -> convert(f, null)).sorted((r1,r2)->r2.getCreateTime().compareTo(r1.getCreateTime())).collect(Collectors.toList()));
        }

        return new MessageOutput<>(new State(CommonConstant.SUCCESS_CODE), pageResult);

    }


    @ApiOperation(value = "获取用户的所有反馈",notes = "获取用户的所有反馈" ,httpMethod = "GET")
    @RequestMapping(value = "/userFeedbackList",method = RequestMethod.GET)
    public List<FeedbackEntity> getUserFeedbackList(@RequestParam(name = "userId", required = true) String userId)
    {
        return feedbackService.getComments(userId); //查询出用户评论
    }

    @ApiOperation(value = "获取该意见下所有回复列表",notes = "获取该意见下所有回复列表" ,httpMethod = "GET")
    @RequestMapping(value = "/userReplyList",method = RequestMethod.GET)
    public List<FeedbackEntity> getReplyList(@RequestParam(name = "id", required = true) Integer id)
    {
        return feedbackService.getReply(id);
    }

    @ApiOperation(value = "删除反馈和反馈下的回复",notes = "删除反馈和反馈下的回复" ,httpMethod = "DELETE")
    @RequestMapping(value = "/deleteFeedback",method = RequestMethod.DELETE)
    public MessageOutput<Object> deleteFeedback(@RequestBody JSONObject idObject) throws Exception{
        if(feedbackService.deleteFeedback(idObject.getInteger("id")))
            return new MessageOutput<Object>(new State(ResultCodeEnum.SUCCESS.getCode(), "删除成功"));
        else
            return new MessageOutput<Object>(new State(ResultCodeEnum.FAILED.getCode(),"删除失败"));
    }

    @ApiOperation(value = "删除某条回复",notes = "删除某条回复" ,httpMethod = "DELETE")
    @RequestMapping(value = "/reply",method = RequestMethod.DELETE)
    public MessageOutput<Object> deleteReply(@RequestBody JSONObject idObject) throws Exception{
        if(feedbackService.deleteReoly(idObject.getInteger("id")))
            return new MessageOutput<>(new State(ResultCodeEnum.SUCCESS.getCode(), "删除成功"));
        else
            return new MessageOutput<>(new State(ResultCodeEnum.FAILED.getCode(),"删除失败"));
    }

    @ApiOperation(value = "删除回复列表",notes = "删除回复列表" ,httpMethod = "DELETE")
    @RequestMapping(value = "/replyList",method = RequestMethod.DELETE)
    public MessageOutput<Object> deleteReplyList(@RequestBody JSONObject idObject) throws Exception{
        if(feedbackService.deleteReolyList(idObject.getInteger("id")))
            return new MessageOutput<>(new State(ResultCodeEnum.SUCCESS.getCode(), "删除成功"));
        else
            return new MessageOutput<>(new State(ResultCodeEnum.FAILED.getCode(),"删除失败"));
    }


    private FeedbackEntity voConvert(FeedbackVO feedbackVO){
        if(feedbackVO == null)
            return null;
        FeedbackEntity feedbackEntity = new FeedbackEntity();
        feedbackEntity.setTitle(feedbackVO.getTitle());
        feedbackEntity.setContent(feedbackVO.getDescribe());
        feedbackEntity.setUserId(feedbackVO.getUserId());
        if(null == feedbackVO.getOriginId() || 0 == feedbackVO.getOriginId() )
            feedbackEntity.setOriginId(0);
        else
            feedbackEntity.setOriginId(feedbackVO.getOriginId());
        JSONObject contact = new JSONObject();
        contact.put("feedbackPerson",feedbackVO.getFeedbackPerson());
        contact.put("tele",feedbackVO.getTele());
        contact.put("company",feedbackVO.getCompany());
        contact.put("email",feedbackVO.getEmail());
        feedbackEntity.setContact(contact.toString());
        return feedbackEntity;
    }

    private FeedbackVO convert (FeedbackEntity feedbackEntity, List<FeedbackEntity> replyList)
    {
        FeedbackVO feedbackVO = new FeedbackVO();
        feedbackVO.setTitle(feedbackEntity.getTitle());
        feedbackVO.setDescribe(feedbackEntity.getContent());
        feedbackVO.setId(feedbackEntity.getId());
        feedbackVO.setIsDelete(feedbackEntity.getIsDelete());
        feedbackVO.setCreateTime(feedbackEntity.getCreateTime());
        JSONObject jsonContact = JSONObject.parseObject(feedbackEntity.getContact());
        String feedbackPerson = jsonContact.getString("feedbackPerson");
        String tele = jsonContact.getString("tele");
        String company = jsonContact.getString("company");
        String email = jsonContact.getString("email");
        feedbackVO.setFeedbackPerson(feedbackPerson);
        feedbackVO.setTele(tele);
        feedbackVO.setCompany(company);
        feedbackVO.setEmail(email);
        feedbackVO.setUserId(feedbackEntity.getUserId());
        if(null != replyList && replyList.size() >= 1)
        {
            ReplyVO replyVO = new ReplyVO();
            replyVO.setId(replyList.get(0).getId());
            replyVO.setQuestion(replyList.get(0).getContent());
            replyVO.setCreateTime(replyList.get(0).getCreateTime());
            replyVO.setIsDelete(replyList.get(0).getIsDelete());
            List<ReplyVO> replyVOList = new ArrayList<>();
            replyVOList.add(replyVO);
            feedbackVO.setReplyList(replyVOList);
        }
        return feedbackVO;
    }
}
